package cn.wqb.wallet.filter;

import cn.wqb.wallet.jwt.JWTUtils;
import cn.wqb.wallet.jwt.Token;
import cn.wqb.wallet.jwt.TokenUtils;
import cn.wqb.wallet.utils.IPUtils;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/admin/*")
public class TokenFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        Token token = TokenUtils.getTokenFromRequest(request);
        if (token == null) {
            returnTokenInvalid(servletRequest, servletResponse);
            return;
        }
        String ip = IPUtils.getClientIPFromRequest(request);
        Token newToken = JWTUtils.parseAndReturnNewToken(token, ip);
        if (newToken == null || StringUtils.isEmpty(newToken.getToken())) {
            returnTokenInvalid(servletRequest, servletResponse);
            return;
        }
        //放行
        TokenUtils.updateTokenToCookie(response, newToken);
        filterChain.doFilter(servletRequest, servletResponse);
    }

    private void returnTokenInvalid(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        servletRequest.getRequestDispatcher("/tokenInvalid").forward(servletRequest, servletResponse);
    }
}
